package com.derbysoft.synxisadapter.dswitch2.service.impl;

import com.derbysoft.synxisadapter.commons.repository.TransactionLogRepository;
import com.derbysoft.synxisadapter.dswitch2.service.RemoveExpiredDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RemoveExpiredDataServiceImpl implements RemoveExpiredDataService {

    public static final int STEP = 100;
    private static Logger logger = LoggerFactory.getLogger(RemoveExpiredDataServiceImpl.class);

    public static final int TWO_MONTHS = 60;
    public static final int ONE_HUNDRED = 1000;
    private static final int BATCH_SIZE = ONE_HUNDRED;

    private TransactionLogRepository transactionLogRepository;

    private int keepSuccessLogDays = TWO_MONTHS;
    private int keepExceptionLogDays = TWO_MONTHS;


    @Override
    public void invoke() {
        if (transactionLogRepository == null) {
            return;
        }

        logger.info("Remove expired logs BEGIN!");

        removeLog(keepExceptionLogDays, true);
        removeLog(keepSuccessLogDays, false);

        logger.info("Remove expired logs END!");
    }

    private void removeLog(int keepDays, boolean error) {
        for (int i = 0; i < STEP; i++) {
            int removeCount = transactionLogRepository.removeExpired(keepDays, error, BATCH_SIZE);
            if (removeCount < BATCH_SIZE / 2) {
                break;
            }
        }
    }

    public void setTransactionLogRepository(TransactionLogRepository transactionLogRepository) {
        this.transactionLogRepository = transactionLogRepository;
    }

    public void setKeepSuccessLogDays(int keepSuccessLogDays) {
        this.keepSuccessLogDays = keepSuccessLogDays;
    }

    public void setKeepExceptionLogDays(int keepExceptionLogDays) {
        this.keepExceptionLogDays = keepExceptionLogDays;
    }
}

